/* eslint-disable react/jsx-no-bind */
import React, { forwardRef, useRef, useState } from 'react';
import { useSelector } from 'dva';
import { Checkbox, Col, Row, Form, Button } from 'antd';

const FormItem = Form.Item;

/**
 * 导出对账单，表格字段
 *  */
const ChooseFields = forwardRef((props, ref) => {
  const { value, onChange } = props;
  const {
    sendreceiveInfo = {},
    orderInfo = {},
    lanjianInfo = {},
    weightPriceInfo = {},
    timeInfo = {},
  } = useSelector(({ order }) => order.exportOrderConfig);

  const arr = [
    {
      label: '收发件信息',
      key: 'sendreceiveInfo',
      value: sendreceiveInfo,
    },
    {
      label: '订单信息',
      key: 'orderInfo',
      value: orderInfo,
    },
    {
      label: '揽件信息',
      key: 'lanjianInfo',
      value: lanjianInfo,
    },
    {
      label: '重量和运费',
      key: 'weightPriceInfo',
      value: weightPriceInfo,
    },
    {
      label: '时间',
      key: 'timeInfo',
      value: timeInfo,
    },
  ];

  const [selectAll, setSelectAll] = useState(false);
  const count = useRef(value.length);

  const handelSelect = key => {
    const total = arr.map(v => [...Object.keys(v.value)]).flat().length;
    count.current = value.length;

    const index = value.findIndex(v => v == key);
    if (index >= 0) {
      value.splice(index, 1);
      count.current -= 1;
    } else {
      value.push(key);
      count.current += 1;
    }
    setSelectAll(total == count.current);
    onChange(value);
  };

  const handelSelectAll = e => {
    const { checked } = e.target;
    setSelectAll(checked);
    if (checked) {
      const _arr = [];
      arr.forEach(v => {
        Object.keys(v.value).forEach(i => _arr.push(i));
      });
      onChange(_arr);
    } else {
      count.current = 0;
      onChange([]);
    }
  };
  return (
    <Row style={{ marginLeft: 20 }}>
      <Col>
        <span style={{ fontSize: 16, fontWeight: 'bold' }}>导出表格字段设置：</span>
        <Checkbox ref={ref} checked={selectAll} onChange={handelSelectAll}>
          全选
        </Checkbox>
      </Col>
      <Col>
        {arr.map(item => {
          const { key, label, value: _value } = item;
          return (
            <FormItem style={{ marginBottom: 0 }} label={label} key={key}>
              {Object.keys(_value).map(_key => {
                const checked = value.includes(_key);
                return (
                  <Button
                    ghost={checked}
                    type={checked ? 'primary' : 'default'}
                    onClick={handelSelect.bind(null, _key)}
                    value={_key}
                    key={_key}
                    style={{ marginRight: 10 }}
                  >
                    {_value[_key]}
                  </Button>
                );
              })}
            </FormItem>
          );
        })}
      </Col>
    </Row>
  );
});

export default ChooseFields;
